package com.lagou.filter;

import com.lagou.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @ClassName: TokenFilter
 * @Auther: Jerry
 * @Date: 2020/10/23 16:27
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    private static final String AUTHORIZE_TOKEN = "lg_token";

    /**
     * 需要排除拦截的路径
     */
    private static final String EXCLUDE_PATH = "/api/user/**,/api/code/**";

    private PathMatcher matcher = new AntPathMatcher();

    @Reference
    private UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应
        ServerHttpResponse response = exchange.getResponse();
        // 添加全局过滤，进行token的验证，
        String uriPath = request.getURI().getPath();
        // /api/user/register/gmh0612@163.com/123456/728149
        logger.info("req param[uriPath={}]", uriPath);
        // 用户微服务和验证码微服务的请求放行
        if (match(EXCLUDE_PATH, uriPath)) {
            return chain.filter(exchange);
        }
        MultiValueMap<String, HttpCookie> multiValueMap = exchange.getRequest().getCookies();
        List<HttpCookie> cookies =  multiValueMap.get(AUTHORIZE_TOKEN);

        if (!CollectionUtils.isEmpty(cookies)) {
            String token = cookies.get(0).getValue();
            System.out.println(token);
            // token为空 不放行
            if (StringUtils.isBlank(token)) {
                response.setStatusCode(HttpStatus.FORBIDDEN);
                return response.setComplete();
            }
            // 校验token,token不正确会返回null，token正确会返回用户邮箱
            String info = userService.info(token).getData().getEmail();
            System.out.println(info);
            // 邮箱为空，不放行
            if (StringUtils.isBlank(info)) {
                response.setStatusCode(HttpStatus.FORBIDDEN);
                return response.setComplete();
            }
            return chain.filter(exchange);
        }
        // 没有cookie不放行
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    private boolean match(String excludePath, String urlPath){
        String[] excludePaths = excludePath.split(",");
        if (excludePaths != null && excludePaths.length > 0) {
            for (String path : excludePaths) {
                boolean match = matcher.match(path, urlPath);
                if (match) {
                    System.out.println("url 匹配上了");
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
